import React from 'react';
import { withRouter } from 'react-router-dom';

import { Button, Input, Space, Table, Popconfirm, Descriptions, notification as Notification } from 'antd';
import { DownOutlined, ReloadOutlined, RightOutlined, SearchOutlined } from '@ant-design/icons';
import Highlighter from 'react-highlight-words';

import './BookMy.scss';
import { listBookInfo, revertBook } from '../../../api/bookInfo';
import moment from 'moment';

const format = 'yyyy-MM-DD HH:mm:ss';

class BookMy extends React.Component {
  state = {
    user: {},
    tableLoading: false,
    tableHeight: 400,
    tableData: [],
    tableParam: {},
    pagination: {
      current: 1,
      pageSize: 10,
      total: 1,
      showTotal: (total) => `共 ${total} 条`,
      hideOnSinglePage: false
    },
    searchText: {}
  };

  constructor(props) {
    super(props);
    const { user } = JSON.parse(localStorage.getItem('user') || '{}');
    this.state = {
      user: user || {},
      tableLoading: false,
      tableHeight: 400,
      tableData: [],
      tableParam: {},
      pagination: {
        current: 1,
        pageSize: 10,
        total: 1,
        showTotal: (total) => `共 ${total} 条`,
        hideOnSinglePage: false
      },
      searchText: {}
    };
  }

  componentDidMount() {
    const { pagination } = this.state;
    this.fetch(pagination);

    window.addEventListener('resize', this.handleResize);
    setTimeout(() => {
      this.handleResize();
    }, 1);
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this.handleResize);
  }

  handleResize = (e) => {
    const element = document.getElementsByClassName('book-my-container')[0];
    if (element) {
      const offsetHeight = element.offsetHeight;
      const tableHeight = offsetHeight - 64 - 58 - 4;
      this.setState({
        tableHeight: tableHeight
      });
    }
  };

  handleSearch = (selectedKeys, confirm, dataIndex) => {
    const { searchText } = this.state;
    const state = Object.assign(searchText, {
      [dataIndex]: selectedKeys && selectedKeys[0]
    });
    this.setState(state);
    confirm();
  };

  getColumnSearchProps = (dataIndex, placeholder) => ({
    filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
      <div style={{ padding: 8 }}>
        <Input
          ref={(node) => {
            this.searchInput = node;
          }}
          placeholder={placeholder}
          value={selectedKeys[0]}
          onChange={(e) => setSelectedKeys(e.target.value ? [e.target.value] : [])}
          onPressEnter={() => this.handleSearch(selectedKeys, confirm, dataIndex)}
          style={{ width: 130, marginBottom: 8, display: 'block' }}
        />
        <Space>
          <Button onClick={() => this.handleReset(clearFilters)} size="small" style={{ width: 60 }}>
            清空
          </Button>
          <Button
            type="primary"
            onClick={() => this.handleSearch(selectedKeys, confirm, dataIndex)}
            icon={<SearchOutlined/>}
            size="small"
            style={{ width: 60 }}
          >
            查找
          </Button>
        </Space>
      </div>
    ),
    filterIcon: (filtered) => <SearchOutlined style={{ color: filtered ? '#1890ff' : undefined }}/>,
    onFilter: (value, record) => true,
    onFilterDropdownVisibleChange: (visible) => {
      if (visible) {
        setTimeout(() => this.searchInput.select(), 100);
      }
    },
    render: (text) => {
      const searchText = this.state.searchText[dataIndex];
      return searchText ? (
        <Highlighter
          highlightStyle={{ backgroundColor: '#ffc069', padding: 0 }}
          searchWords={[searchText]}
          autoEscape
          textToHighlight={text ? text.toString() : ''}
        />
      ) : (text);
    }
  });

  handleReset = (clearFilters) => {
    clearFilters();
    const state = Object.assign(this.state, {
      searchText: ''
    });
    this.setState(state);
  };

  handleTableChange = (pagination, filters, sorter) => {
    const { isbn, borrowed } = filters;
    const { field, order } = sorter;

    const params = {
      isbn: isbn && isbn[0],
      borrowed: borrowed && borrowed[0],
      sortField: field,
      order: order && order.replace('end', ''),
    };

    this.setState({
      tableParam: params
    });
    this.fetch(pagination, params);
  };

  handleRefresh = () => {
    this.fetch(this.state.pagination, this.state.tableParam);
  };

  fetch = (pagination = {}, params = {}) => {
    const { user: { id: userId }} = this.state;
    this.setState({ tableLoading: true });
    const { current: pageNum, pageSize } = pagination;

    if (!userId) {
      Notification.error({
        message: '未读取到用户信息，请重新登录',
        duration: 5
      });
      return;
    }

    Object.assign(params, {
      borrowUserId: userId
    });
    listBookInfo(pageNum, pageSize, params).then(({ data }) => {
      const { pageNum, pageSize, total, list } = data;

      const pagination = Object.assign(this.state.pagination, {
        current: pageNum,
        pageSize: pageSize,
        total: total
      });

      this.setState({
        tableData: list,
        pagination
      });
    }).catch((e) => {
      console.log(e, typeof e, 'listBookInfo e');
    }).finally(() => {
      this.setState({ tableLoading: false });
    });
  };

  revertBook=(record) => {
    console.log(record, typeof record, 'record');
    console.log(moment(), typeof moment(), 'moment(text, format)');
    const { id } = record;
    const { user: { id: borrowUserId }} = this.state;

    revertBook({ id, borrowUserId }).then(({ data }) => {
      Notification.success({
        message: `归还 ${data.name} 成功`,
        duration: 2
      });
      this.handleRefresh();
    }).catch((e) => {
      console.log(e, typeof e, 'listBookInfo e');
    });
  };

  render() {
    const { tableData, pagination, tableLoading, tableHeight } = this.state;

    const columns = [
      {
        title: 'ISBN',
        dataIndex: 'isbn',
        width: 200,
        sortDirections: ['ascend', 'descend', 'ascend'],
        sorter: true,
        ...this.getColumnSearchProps('isbn', '请输入查找 ISBN'),
      },
      {
        title: '书籍名称',
        dataIndex: 'name',
        width: 350,
      },
      {
        title: '借阅时间',
        dataIndex: 'borrowedTime',
        width: 200,
      },
      {
        title: '预计归还时间',
        dataIndex: 'expectedReturnTime',
        width: 200,
        render: (text) => {
          const timeOut = moment(text, format).diff(moment(), 'days') < 0;
          return timeOut ? (<span style={{ color: 'red' }}>{text}</span>) : (text);
        }
      },
      {
        title: '操作',
        dataIndex: 'operation',
        render: (text, record) => (
          <Space size="middle">
            <Popconfirm
              title="确认删除?"
              cancelText="取消"
              okText="确定"
              okType=""
              onConfirm={() => this.revertBook(record)}>
              <a>立即归还</a>
            </Popconfirm>
          </Space>
        )
      },
    ];

    const expandable = {
      expandIcon: ({ expanded, onExpand, record }) =>
        expanded ? (
          <DownOutlined onClick={(e) => onExpand(record, e)}/>
        ) : (
          <RightOutlined onClick={(e) => onExpand(record, e)}/>
        ),
      expandIconColumnIndex: 4,
      expandedRowRender: (record) => (
        <Descriptions
          bordered
          title="更多信息"
          column={1}
        >
          <Descriptions.Item label="作者:">{record.author}</Descriptions.Item>
          <Descriptions.Item label="出版社:">{record.publisher}</Descriptions.Item>
          <Descriptions.Item label="分享者:">{record.ownerUserName}</Descriptions.Item>
          <Descriptions.Item label="分享时间:">{record.createTime}</Descriptions.Item>
        </Descriptions>
      ),
      rowExpandable: (record) => true,
    };

    return (
      <div className="book-my-container">
        <Space style={{ marginBottom: 10 }}>
          <Button type="primary" icon={<ReloadOutlined/>} onClick={this.handleRefresh} disabled={tableLoading}
            loading={tableLoading}>刷新</Button>
        </Space>
        <div className="book-table-wrapper">
          <Table
            columns={columns}
            rowKey={(data) => data.id}
            dataSource={tableData}
            pagination={pagination}
            loading={tableLoading}
            bordered
            showSorterTooltip={false}
            onChange={this.handleTableChange}
            expandable={expandable}
            scroll={{ y: tableHeight }}
          />
        </div>
      </div>
    );
  }
}

export default withRouter(BookMy);
